from cozepy import COZE_CN_BASE_URL
from cozepy import Coze, TokenAuth, Message, ChatStatus, MessageContentType, ChatEventType
from pathlib import Path
import os
import re
import hashlib
import json
import requests
import checkurl
import time
from deal_result import load_json_result, write_result_excel_v3


class AnalyzerCoze:
    def __init__(self):
        self.bot_id = '7527516233181642795'  # 智能体ID
        self.user_id = '123456780'  # 用户ID
        self.coze_api_token = 'pat_9VyNOdGyxFOJqauLxxXkkEj9F1CUXwaLWD57RIjJOTEtOQ3QTyoU6iuCvd5CFqlx'
        self.coze_api_base = COZE_CN_BASE_URL
        self.cache_dir = Path('.code_cache')
        if not os.path.exists(self.cache_dir):
            os.mkdir(self.cache_dir)
        self.sort_txt_path = '.code_cache/sort.txt'
        self.session_id = ''
        # 先删除sort.txt
        try:
            os.remove(self.sort_txt_path)
        except FileNotFoundError:
            pass

    def analyze_html_file(self, html_file: str, article_url, product, name, fail_urls):
        """分析HTML文件"""
        cache_key = self._generate_cache_key(article_url)
        # 写入sort.txt后续按序号读取json文件
        with open(self.sort_txt_path, 'a', encoding='utf-8') as f:
            f.write(name + "---" + cache_key + '.json\n')

        with open(html_file, 'r', encoding='utf-8') as f:
            cleaned_content = []  # 存储处理后的每一行
            for line in f:
                if not re.search(r'!\[.*?\]\(.*?\)', line):
                    cleaned_content.append(line)
            html = ''.join(cleaned_content)
        result = self.analyzer_coze_cloud(html, article_url)
        result['类型'] = product
        result['文章名称'] = name
        result['链接问题'] = fail_urls
        self.save_result_to_json(cache_key, result)
        return result

    def analyze_md_content(self, md_content, article_url, product, name):
        """分析MarkDown"""
        cache_key = self._generate_cache_key(article_url)
        # 写入sort.txt后续按序号读取json文件
        with open(self.sort_txt_path, 'a', encoding='utf-8') as f:
            f.write(cache_key + '.json\n')
        result = self.analyzer_coze_cloud(md_content, article_url)
        result['类型'] = product
        result['文章名称'] = name
        self.save_result_to_json(cache_key, result)

        return result

    def _generate_cache_key(self, url: str):
        """生成缓存文件名"""
        return hashlib.md5(url.encode()).hexdigest()

    def analyzer_coze_cloud(self, html, article_url):
        """调用coze 智能体 API分析代码语法"""
        cache_key = self._generate_cache_key(article_url)
        cached_result = self._load_from_cache(cache_key)
        if cached_result:
            print(cached_result)
            return cached_result

        result = ''
        prompt = f"""待分析文章如下：\n{html}"""
        self.message = prompt
        coze = Coze(auth=TokenAuth(token=self.coze_api_token), base_url=self.coze_api_base)
        try:
            for event in coze.chat.stream(
                    bot_id=self.bot_id,
                    user_id=self.user_id,
                    additional_messages=[
                        Message.build_user_question_text(self.message),
                    ],
            ):
                if event.event == ChatEventType.CONVERSATION_MESSAGE_DELTA:
                    print(event.message.content, end="", flush=True)
                    result += event.message.content

                if event.event == ChatEventType.CONVERSATION_CHAT_COMPLETED:
                    print()
                    print("token usage:", event.chat.usage.token_count)
                    print("out token usage:", event.chat.usage.output_count)
                    print("in token usage:", event.chat.usage.input_count)

            start = result.find('{')
            end = result.rfind('}')
            content = result[start:end + 1]
            content = content.replace('="', '=')
            content = content.replace('">', '>')
            # content = data['payload']['content'][8:].split('```')[0]
            result = json.loads(content)
            return result
        except Exception as e:
            return {
                "error": f"API调用失败: {str(e)}",
                "data": result
            }

    def save_result_to_json(self, key: str, result):
        with open(self.cache_dir / f'{key}.json', 'w', encoding='utf-8') as f:
            json.dump(result, f, ensure_ascii=False, indent=2)

    def _load_from_cache(self, key: str):
        cache_file = self.cache_dir / f'{key}.json'
        if cache_file.exists():
            with open(cache_file, 'r', encoding='utf-8') as f:
                return json.load(f)
        return None


def main():
    ai = AnalyzerCoze()
    with open('1.html', 'r', encoding='utf-8') as f:
        html_content = f.read()
    result = checkurl.main(html_content, '')
    ai.analyze_html_file(f'1.md',
                         f'https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/serializable-overviewtestmd2',
                         '指南',
                         f'test.md', result)
    analyzer_results = load_json_result('.code_cache')
    write_result_excel_v3(analyzer_results)


if __name__ == '__main__':
    s = time.time()
    main()
    e = time.time()
    print(e - s)
